<?php
namespace app\api\validate;

use app\common\validate\BaseValidate;
use app\facade\model\AdminUser as ModelAdminUser;

/**
 * 登录
 */
class AdminUser extends BaseValidate {
    protected $rule = [
        'id' 		   => 'require|isNotEmpty|gt:0',
        'username'     => 'require|min:1|isUnique',
        'password'     => 'min:6|max:32',
        'description'  => 'max:100',
        'nickname'     => 'max:100',
        // 'avatar'    => 'require|url',
        'role_ids'     => 'regex:ids',
        'phone'        => 'phone|isUnique'
    ];

    protected $message = [
        'id.gt' 		       => 'id必须为正整数.',
        'id.require' 	       => 'id是为必须的参数.',
        'id.isNotEmpty'        => 'id不能为空.',
        'username.isUnique'    => '用户名已经存在了',
        'phone.isUnique'       => '手机号已经存在了',
    ];

    protected $scene = [
        'save'   => ['username','password','description','nickname','avatar','role_ids','phone'],
        'update' => ['id','username','password','description','nickname','avatar','role_ids','phone'],
        'id'     => ['id']
    ];

    protected function isUnique($name, $tmp, $data, $field) {
        $where = [];
        $where[] = [$field, '=', $name];
        if($id = request()->id) {
            $where[] = ['id', '<>', $id];
        }
        $user = ModelAdminUser::getRow($where);
        if(!$user->isEmpty()) {
            return false;
        }
        return true;
    }
}